package com.un.ebs.customer.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.un.ebs.core.UserContext;
import com.un.ebs.core.enums.PowerTypeEnum;
import com.un.ebs.core.enums.UserTypeEnum;
import com.un.ebs.core.exception.BusinessEntityNotFoundException;
import com.un.ebs.core.exception.BusinessException;
import com.un.ebs.core.power.PowerResourceObject;
import com.un.ebs.core.power.PowerResourceSet;
import com.un.ebs.core.util.SecurityUtils;
import com.un.ebs.core.util.StringUtils;
import com.un.ebs.customer.CustomerConfigureCode;
import com.un.ebs.customer.domain.Customer;
import com.un.ebs.customer.domain.CustomerAndDefunctExt;
import com.un.ebs.customer.domain.CustomerExt;
import com.un.ebs.customer.domain.CustomerTrace;
import com.un.ebs.customer.dto.CustomerAddBySuggestDto;
import com.un.ebs.customer.dto.CustomerAddDto;
import com.un.ebs.customer.dto.CustomerRealNameBindRequest;
import com.un.ebs.customer.dto.CustomerUpdateDto;
import com.un.ebs.customer.enums.CustomerStatusEnum;
import com.un.ebs.customer.enums.RemindTypeEnum;
import com.un.ebs.customer.event.CustomerTraceEvent;
import com.un.ebs.customer.mapper.CustomerAndDefunctExtMapper;
import com.un.ebs.customer.mapper.CustomerExtMapper;
import com.un.ebs.customer.mapper.CustomerMapper;
import com.un.ebs.customer.mapper.CustomerTraceMapper;
import com.un.ebs.customer.service.CustomerService;
import com.un.ebs.customer.vo.CustomerOrderVo;
import com.un.ebs.order.domain.OrderExt;
import com.un.ebs.order.mapper.OrderMapper;
import com.un.ebs.order.service.OrderService;
import com.un.ebs.sys.domain.AppUserRoleExt;
import com.un.ebs.sys.domain.DictionaryValueExt;
import com.un.ebs.sys.domain.Personnel;
import com.un.ebs.sys.domain.User;
import com.un.ebs.sys.dto.AddressDto;
import com.un.ebs.sys.service.*;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author liubo
 * @since 2019-09-24
 */
@Service
public class CustomerServiceImpl extends ServiceImpl<CustomerMapper, Customer> implements CustomerService {

    @Resource
    private CustomerAndDefunctExtMapper customerAndDefunctExtMapper;

    @Resource
    private UserService userService;

    @Resource
    private PersonnelService personnelService;

    @Resource
    private CustomerExtMapper customerExtMapper;

    @Resource
    private CustomerMapper customerMapper;

    @Resource
    private CustomerTraceMapper customerTraceMapper;

    @Resource
    private AppTenantService appTenantService;

    @Resource
    private DictionaryValueService dictionaryValueService;

    @Resource
    private AppPowerService appPowerService;

    @Resource
    private ConfigureService configureService;

    @Resource
    private OrderMapper orderMapper;

    @Resource
    private OrderService orderService;

    @Override
    public String add(String name, String phone, String openId) {
        CustomerAddDto req = new CustomerAddDto();
        req.setName(name);
        req.setPhone(phone);
        req.setWechatId(openId);

        // 验证客户来源的值
//        dictionaryValueService.hasValue(CustomerConfigureCode.customer_source_dict, "wx", "微信公众号", true);
//        req.setSourceDict("wx");

        // 取客户等级的第一个值为默认值
//        Optional<DictionaryValueExt> obj = dictionaryValueService.queryValueByKey(CustomerConfigureCode.customer_level).stream().findFirst();
//        if (obj.isPresent()) {
//            req.setLevelDict(obj.get().getValue());
//        }
        return add(req);
    }

    @Transactional
    @Override
    public String add(CustomerAddBySuggestDto req) {
        CustomerAddDto obj = new CustomerAddDto();
        obj.setName(req.getName());
        obj.setPhone(req.getPhone());
        obj.setSex(req.getSex().getCode());

        Customer cust = queryByUserId(SecurityUtils.getUserContent().getId());
        if (cust == null) {
            throw new BusinessException("你没有权限进行此操作。");
        }
        obj.setSuggestCustomerId(cust.getId());
        obj.setRemark(req.getRemark());

        if (!StringUtils.isNullOrEmpty(req.getSourceCustomerName())) {
            cust.setPhone(req.getSourceCustomerPhone());
            cust.setName(req.getSourceCustomerName());
            cust.updateById();
        }
        return add(obj);
    }

    @CacheEvict(cacheNames = "customer", allEntries = true)
    @Transactional
    @Override
    public String add(CustomerAddDto req) {
        if (!StringUtils.isMobile(req.getPhone())) {
            throw new BusinessException("请填写有效的手机号码【" + req.getPhone() + "】。");
        }
        checkCustomer(req.getPhone(), SecurityUtils.getTenantId());
        Customer obj = new Customer();
        obj.setName(req.getName());
        obj.setIdNumber(req.getIdNumber());
        obj.setBirthday(req.getBirthday());
        obj.setProvinceId(req.getProvinceId());
        obj.setCityId(req.getCityId());
        obj.setCountyId(req.getCountyId());
        obj.setSex(req.getSex());
        obj.setPhone(req.getPhone());
        obj.setAddress(req.getAddress());
        obj.setOtherName(req.getOtherName());
        obj.setOtherPhone(req.getOtherPhone());
        obj.setWechatId(req.getWechatId());
        obj.setEmail(req.getEmail());
        obj.setSourceDict(req.getSourceDict());
        obj.setLevelDict(req.getLevelDict());
        obj.setUserId(req.getUserId());
        obj.setIsDelete(false);
        obj.setSuggestCustomerId(req.getSuggestCustomerId());
        obj.setTenantId(SecurityUtils.getUserContent().getTenantId());

        if (StringUtils.isNullOrEmpty(req.getPersonnelId())) {
            obj.setPersonnelId(SecurityUtils.getUserContent().getPersonnelId());
        }
        obj.insert();

        if (StringUtils.isNullOrEmpty(req.getRemark())) {
            CustomerTraceEvent.publishEvent(this, obj.getId(), CustomerConfigureCode.customer_trace_dict_create);
        } else {
            CustomerTraceEvent.publishEvent(this, obj.getId(), CustomerConfigureCode.customer_trace_dict_create, req.getRemark());
        }
        return obj.getId();
    }

    @Override
    public boolean hasQueryAllPower() {
        String codes = configureService.getValueByCode(CustomerConfigureCode.configure_query_customer_all_role);
        if (StringUtils.isNullOrEmpty(codes)) {
            return false;
        }

        List<AppUserRoleExt> list = userService.queryCurrRoles();
        if (StringUtils.isNullOrEmpty(list)) {
            return false;
        } else {
            return list.stream().filter(s -> codes.contains(s.getCode())).count() > 0;
        }
    }

    @Override
    public void update(String id, String openId, String name, String phone) {
        Customer obj = baseMapper.selectById(id);
        if (obj == null) {
            throw new BusinessEntityNotFoundException(id, "客户");
        }
        obj.setPhone(phone);
        obj.setWechatId(openId);
        obj.setName(name);
        obj.updateById();
    }

    @CacheEvict(cacheNames = "customer", allEntries = true)
    @Override
    public void update(CustomerUpdateDto req) {
        if (!StringUtils.isMobile(req.getPhone())) {
            throw new BusinessException("请填写有效的手机号码。");
        }
        //checkCustomer(req.getPhone(), SecurityUtils.getTenantId());
        Customer obj = getById(req.getId());
        obj.setName(req.getName());
        obj.setIdNumber(req.getIdNumber());
        obj.setBirthday(req.getBirthday());
        obj.setSex(req.getSex());
        obj.setProvinceId(req.getProvinceId());
        obj.setCityId(req.getCityId());
        obj.setCountyId(req.getCountyId());
        obj.setPhone(req.getPhone());
        obj.setAddress(req.getAddress());
        obj.setOtherName(req.getOtherName());
        obj.setOtherPhone(req.getOtherPhone());
        obj.setWechatId(req.getWechatId());
        obj.setEmail(req.getEmail());
        obj.setPersonnelId(req.getPersonnelId());
        obj.setSourceDict(req.getSourceDict());
        obj.setLevelDict(req.getLevelDict());
        obj.setUserId(req.getUserId());
        obj.updateById();

        CustomerTraceEvent.publishEvent(this, obj.getId(), CustomerConfigureCode.customer_trace_dict_update);
    }

    @Transactional
    @Override
    public void update(CustomerRealNameBindRequest req) {
        List<CustomerExt> custs = queryViewByOpenId(req.getOpenId());
        if (StringUtils.isNullOrEmpty(custs)) {
            LoggerFactory.getLogger(this.getClass().getName()).warn(String.format("当前微信用户没有客户信息。 openId : %s", req.getOpenId()));
            throw new BusinessException("当前微信用户没有客户信息。");
        }
        if (custs.size() > 1) {
            LoggerFactory.getLogger(this.getClass().getName()).warn(String.format("当前openId绑定了多个客户数据，请联系管理员合并客户数据。 openId : %s , phone : %s", req.getOpenId(), req.getPhone()));
            throw new BusinessException("客户数据异常，请联系管理员合并客户数据。");
        }
        for (CustomerExt cust : custs) {
            Customer obj = queryById(cust.getId());
            obj.setName(req.getName());
            obj.setSex(req.getSex().getCode());
            obj.setPhone(req.getPhone());
            obj.updateById();
        }
//        CustomerUpdateDto obj = new CustomerUpdateDto();
//        obj.setId(custs.get(0).getId());
//        obj.setName(req.getName());
//        obj.setSex(req.getSex().getValue());
//        obj.setPhone(req.getPhone());
//        update(obj);
    }

    private void checkCustomer(String phone, String tenantId) {
        Customer cust = baseMapper.selectByPhoneAndTenant(phone, tenantId);
        if (cust != null) {
            Personnel personnel = personnelService.queryById(cust.getPersonnelId());
            if (personnel != null) {
                throw new BusinessException(String.format("%s 此手机号码的客户已存在，业务人员是【%s】，不能重复创建。", phone, personnel.getName()));
            } else {
                throw new BusinessException(String.format("%s 此手机号码的客户已存在，不能重复创建。", phone));
            }

        }
    }

    @Override
    public List<AddressDto> queryAddrByPhone(String phone) {
        return queryAddrByCustomer(baseMapper.selectByPhone(phone));
    }

    @Override
    public List<AddressDto> queryAddrByUserId(String userId) {
        Customer cust = baseMapper.selectByUser(userId);
        return queryAddrByCustomer(cust);
    }

    private List<AddressDto> queryAddrByCustomer(Customer cust) {
        if (cust == null) {
            return new ArrayList<>();
        } else {
            //订单有没有
            List<AddressDto> result = orderMapper.selectByCustId(cust.getId()).stream().map(s -> {
                AddressDto obj = new AddressDto();
                obj.setName(s.getLinkman());
                obj.setPhone(s.getLinkmanPhone());
                obj.setAddr(s.getLinkmanAdd());
                return obj;
            }).filter(s -> !StringUtils.isNullOrEmpty(s.getAddr())).distinct().collect(Collectors.toList());

            //订单没有则取客户中的地址信息
            if (StringUtils.isNullOrEmpty(result)) {
                AddressDto obj = new AddressDto();
                obj.setName(cust.getName());
                obj.setPhone(cust.getPhone());
                obj.setAddr(cust.getAddress());
                result.add(obj);
            }
            return result;
        }
    }

    @Cacheable(cacheNames = "customer", key = "'view-'+#id")
    @Override
    public CustomerExt queryViewById(String id) {
        return customerExtMapper.selectById(id);
    }

    @Cacheable(cacheNames = "customer", key = "#id")
    @Override
    public Customer queryById(String id) {
        return customerMapper.selectById(id);
    }

    @Override
    public Customer queryByUserId(String userId) {
        return customerMapper.selectByUser(userId);
    }

    @Cacheable(cacheNames = "customer", key = "'mobile-'+#id")
    @Override
    public String queryMobile(String id) {
        Customer customer = getById(id);
        if (customer == null) {
            throw new BusinessEntityNotFoundException(id, "客户");
        }

        return customer.getPhone();
    }

    @Cacheable(cacheNames = "customer", key = "'view-mobile'+#phone")
    @Override
    public CustomerExt queryCustViewByMobile(String phone) {
        return customerExtMapper.selectByMobile(phone);
    }

    @Override
    public Customer queryCurrent() {
        LambdaQueryWrapper<Customer> lq = Wrappers.lambdaQuery();
        lq.eq(Customer::getUserId, SecurityUtils.getUserContent().getId());
        Optional<Customer> ret = baseMapper.selectList(lq).stream().findFirst();
        if (ret.isPresent()) {
            return ret.get();
        } else {
            return null;
        }
    }

    @Cacheable(cacheNames = "customer", key = "'mobile'+#phone")
    @Override
    public Customer queryCustByMobile(String phone) {
        return customerMapper.selectByPhone(phone);
    }

    @Cacheable(cacheNames = "customer", key = "'mobile'+#phone")
    @Override
    public Customer queryCustByMobile(String mobile, String tenantId) {
        return customerMapper.selectByPhoneAndTenant(mobile, tenantId);
    }

    @Override
    public Customer queryCustByWx(String openId, String tenantId) {
        return customerMapper.selectByOpenIdAndTenant(openId, tenantId);
    }

    @Override
    public List<String> queryCustIdByUserId(String id) {
        LambdaQueryWrapper<Customer> lq = Wrappers.lambdaQuery();
        lq.eq(Customer::getUserId, id);
        lq.eq(Customer::getTenantId, SecurityUtils.getUserContent().getTenantId());
        List<String> result = baseMapper.selectList(lq).stream().map(s -> s.getId()).collect(Collectors.toList());
        return result;
    }

    @Override
    public List<CustomerExt> queryViewByUserId(String userId) {
        LambdaQueryWrapper<CustomerExt> lq = Wrappers.lambdaQuery();
        lq.eq(CustomerExt::getUserId, userId);
        lq.eq(CustomerExt::getIsDelete, false);
        lq.eq(CustomerExt::getTenantId, SecurityUtils.getUserContent().getTenantId());

        return customerExtMapper.selectList(lq);
    }

    @Override
    public List<CustomerExt> queryViewByOpenId(String openId) {
        String userId = userService.getUserId(openId);
        if (userId == null) {
            return new ArrayList<>();
        }
        return queryViewByUserId(userId);
    }

    @Override
    public List<CustomerOrderVo> queryOrderByCustId(String id) {
        List<String> ids = new ArrayList<>();
        ids.add(id);
        return queryOrderByCustId(ids);
    }

    private List<CustomerOrderVo> queryOrderByCustId(List<String> ids) {
        List<OrderExt> orderExts = orderService.queryByCustId(ids);
        List<CustomerOrderVo> result = new ArrayList<>();
        if (StringUtils.isNullOrEmpty(orderExts)) {
            return result;
        }
        for (OrderExt order : orderExts) {
            CustomerOrderVo vo = new CustomerOrderVo();
            BeanUtils.copyProperties(order, vo);
            vo.setItems(orderService.queryItemViewByOrderId(order.getId()));
            result.add(vo);
        }
        return result;
    }

    @Override
    public List<CustomerOrderVo> queryOrderByDefunctId(String id) {
        LambdaQueryWrapper<CustomerAndDefunctExt> lq = Wrappers.lambdaQuery();
        lq.eq(CustomerAndDefunctExt::getDefunctId, id);
        lq.eq(CustomerAndDefunctExt::getCustomerTenantId, SecurityUtils.getUserContent().getTenantId());
        List<String> custIds = customerAndDefunctExtMapper.selectList(lq).stream().map(s -> s.getCustomerId()).collect(Collectors.toList());
        return queryOrderByCustId(custIds);
    }

    @Override
    public List<CustomerAndDefunctExt> queryCustAndDefunctByDefunctId(String id) {
        LambdaQueryWrapper<CustomerAndDefunctExt> lq = Wrappers.lambdaQuery();
        lq.eq(CustomerAndDefunctExt::getDefunctId, id);
        lq.eq(CustomerAndDefunctExt::getTenantId, SecurityUtils.getUserContent().getTenantId());
        lq.eq(CustomerAndDefunctExt::getCustomerDeleteStatus, false);
        return customerAndDefunctExtMapper.selectList(lq);
    }

    @Override
    public List<CustomerAndDefunctExt> queryCustAndDefunctByCustomerId(String id) {
        LambdaQueryWrapper<CustomerAndDefunctExt> lq = Wrappers.lambdaQuery();
        lq.eq(CustomerAndDefunctExt::getCustomerId, id);
        lq.eq(CustomerAndDefunctExt::getCustomerTenantId, SecurityUtils.getUserContent().getTenantId());
        lq.eq(CustomerAndDefunctExt::getIsDelete, false);
        return customerAndDefunctExtMapper.selectList(lq);
    }

    @Override
    public List<CustomerAndDefunctExt> queryCurrentCustomerAndDefunct() {
        Customer cust = queryByUserId(SecurityUtils.getUserContent().getId());
        if (cust == null) {
            throw new BusinessException("数据异常。");
        }

        LambdaQueryWrapper<CustomerAndDefunctExt> lq = Wrappers.lambdaQuery();
        lq.eq(CustomerAndDefunctExt::getCustomerId, cust.getId());
        return customerAndDefunctExtMapper.selectList(lq);
    }

    @CacheEvict(cacheNames = "customer", allEntries = true)
    @Override
    public void delete(String id) {
        getBaseMapper().deleteById(id);
        CustomerTraceEvent.publishEvent(this, id, CustomerConfigureCode.customer_trace_dict_delete);
    }

    @CacheEvict(cacheNames = "customer", allEntries = true)
    @Transactional
    @Override
    public void changePersonnel(String custId, String personnelId, String remark) {
        Customer customer = getById(custId);
        if (customer == null) {
            throw new BusinessEntityNotFoundException(custId, "客户");
        }
        Personnel personnel = personnelService.queryById(personnelId, UserContext.getInstance().getTenantId());
        if (personnel == null) {
            throw new BusinessEntityNotFoundException(personnelId, "人员");
        }

        customer.setPersonnelId(personnelId);
        customer.updateById();

        String personnelName = personnel.getName();

        // 变更所有计划事件的负责人。
        LambdaQueryWrapper<CustomerTrace> lq = Wrappers.lambdaQuery();
        lq.eq(CustomerTrace::getCustomerId, custId);
        lq.isNull(CustomerTrace::getRealDate);
        List<CustomerTrace> list = customerTraceMapper.selectList(lq);
        for (CustomerTrace item : list) {
            item.setPersonnelId(personnelId);
            item.setPersonnelName(personnelName);
            item.updateById();
        }

        CustomerTraceEvent.publishEvent(this, custId, CustomerConfigureCode.customer_trace_dict_change_person, remark);
    }

    @CacheEvict(cacheNames = "customer", allEntries = true)
    @Transactional
    @Override
    public void changePersonnel(String personnelId, String toPersonnelId) {
        LambdaQueryWrapper<Customer> lq = Wrappers.lambdaQuery();
        lq.eq(Customer::getPersonnelId, personnelId);
        lq.eq(Customer::getIsDelete, false);
        List<Customer> list = baseMapper.selectList(lq);
        for (Customer customer : list) {
            customer.setPersonnelId(toPersonnelId);
            customer.updateById();
            CustomerTraceEvent.publishEvent(this, customer.getId(), CustomerConfigureCode.customer_trace_dict_change_person, "批量变更。");
        }
    }

    @CacheEvict(cacheNames = "customer", allEntries = true)
    @Transactional
    @Override
    public void changePersonnel(String personnelId, List<String> toPersonnelIds) {
        LambdaQueryWrapper<Customer> lq = Wrappers.lambdaQuery();
        lq.eq(Customer::getPersonnelId, personnelId);
        lq.eq(Customer::getIsDelete, false);
        List<Customer> list = baseMapper.selectList(lq);

        if (StringUtils.isNullOrEmpty(list)) {
            throw new BusinessException("指定的业务员名下没有客户。");
        }
        if (list.size() < toPersonnelIds.size()) {
            throw new BusinessException("业务员数量不能多于被分配的客户数量，请减少参与分配的业务员数量。");
        }

        int startIndex = 0;
        int groupCount = list.size() % toPersonnelIds.size() != 0 ? (list.size() + 1) / toPersonnelIds.size() : list.size() / toPersonnelIds.size();
        int groupCurrent = groupCount;
        int groupIndex = 0;

        while (list.size() > startIndex) {
            for (int i = startIndex; i < groupCurrent; i++) {
                if (list.size() > i) {
                    Customer cust = list.get(i);
                    cust.setPersonnelId(toPersonnelIds.get(groupIndex));
                    cust.updateById();
                }
            }
            startIndex += groupCount;
            groupCurrent += groupCount;
            groupIndex += 1;
        }
    }

    @CacheEvict(cacheNames = "customer", allEntries = true)
    @Override
    public void changeLevel(String custId, String levelDict, String remark) {
        Customer customer = getById(custId);
        if (customer == null) {
            throw new BusinessEntityNotFoundException(custId, "客户");
        }
        customer.setLevelDict(levelDict);
        customer.updateById();
        CustomerTraceEvent.publishEvent(this, custId, CustomerConfigureCode.customer_trace_dict_change_level, remark);
    }

    @Override
    public void createRemind(String custId, RemindTypeEnum type, String personnelId, Integer nowPlusDay, String remark) {
//        if(nextVisitDay!=null){
//            CustomerTrace trace = new CustomerTrace();
//            trace.setCustomerId(custId);
//            trace.setTraceDict();
//            trace.setPlanDate(DateUtils.plusDay(nextVisitDay));
//            trace.setPersonnelId(SecurityUtils.getUserContent().getPersonnelId());
//            trace.setPersonnelName(SecurityUtils.getUserContent().getPersonnelName());
//            trace.setRemark(remark);
//            trace.insert();
//        }
    }

    @Override
    public void createRemind(String custId, RemindTypeEnum type, String personnelId, Date remindDate, String remark) {

    }

    @CacheEvict(cacheNames = "customer", allEntries = true)
    @Transactional
    @Override
    public boolean bindToUser(String entId, String phone, String openId) {

        List<String> ids = appTenantService.queryTenantIdByEntId(entId);
        if (ids.size() <= 0) {
            return false;
        }

        List<Customer> customers = baseMapper.selectListByPhone(ids.get(0), phone);
        if (customers.size() <= 0) {
            return false;
        }

        User user = userService.createOpenIdUser(openId, ids.get(0));

        for (Customer cust : customers) {
            cust.setUserId(user.getId());
            cust.updateById();
        }
        return true;
    }

    @CacheEvict(cacheNames = "customer", allEntries = true)
    @Transactional
    @Override
    public void bindToUser(String id, String openId) {
        Customer customer = getById(id);
        if (customer == null) {
            throw new BusinessEntityNotFoundException(id, "客户");
        }

        User user = userService.createOpenIdUser(openId, customer.getTenantId());
        customer.setUserId(user.getId());
        customer.updateById();
    }

    @Override
    public List<CustomerAndDefunctExt> queryBindList(String entId, String searchText) {

        LambdaQueryWrapper<CustomerAndDefunctExt> lq = Wrappers.lambdaQuery();
        lq.eq(CustomerAndDefunctExt::getCustomerEntId, entId);
        lq.and(obj -> obj
                .like(CustomerAndDefunctExt::getCustName, searchText).or()
                .like(CustomerAndDefunctExt::getCustPhone, searchText).or()
                .like(CustomerAndDefunctExt::getCustOtherName, searchText).or()
                .like(CustomerAndDefunctExt::getCustOtherPhone, searchText).or()
                .like(CustomerAndDefunctExt::getDefunctName, searchText).or()
        );
        return customerAndDefunctExtMapper.selectList(lq);
    }

    @Override
    public List<String> queryCustSourcePower() {
        List<String> ids = userService.queryCurrRoles().stream().map(s -> s.getId()).collect(Collectors.toList());
        return appPowerService.queryResourcePower(ids, PowerTypeEnum.Customer_Source);
    }

    @Override
    public IPage<CustomerExt> query(String searchText, String personnelId, CustomerStatusEnum status, int pageSize, int pageIndex) {

        Page<CustomerExt> page = new Page<>(pageIndex, pageSize);
        LambdaQueryWrapper<CustomerExt> lq = Wrappers.lambdaQuery();
        lq.eq(CustomerExt::getIsDelete, false);
        lq.isNotNull(CustomerExt::getPhone);
        if (status != null) {
            lq.eq(CustomerExt::getCustStatus, status);
        }
        if (SecurityUtils.getUserContent().getType() == UserTypeEnum.OTHER) {
            lq.eq(CustomerExt::getCreateAt, SecurityUtils.getUserContent().getId());
            lq.isNotNull(CustomerExt::getSuggestCustomerId);
        } else {
            if (!hasQueryAllPower()) {
                lq.eq(CustomerExt::getPersonnelId, SecurityUtils.getUserContent().getPersonnelId());
            } else {
                if (!StringUtils.isNullOrEmpty(personnelId)) {
                    lq.eq(CustomerExt::getPersonnelId, personnelId);
                }
            }
        }

        // TODO: 2020/2/26 此处有BUG，此处没有根据租户过滤，暂时去掉客户渠道权限
//        List<String> custSourceDicts = queryCustSourcePower();
//        if (custSourceDicts != null) {
//            if (custSourceDicts.size() > 0) {
//                lq.in(CustomerExt::getSourceDict, custSourceDicts);
//            }
//        }

        //lq.eq(CustomerExt::getUserType, UserTypeEnum.OTHER);
        lq.isNotNull(CustomerExt::getPhone);

        if (!StringUtils.isNullOrEmpty(searchText)) {
            lq.and(obj -> obj
                    .like(CustomerExt::getName, searchText).or()
                    .like(CustomerExt::getPhone, searchText).or()
                    .like(CustomerExt::getOtherName, searchText).or()
                    .like(CustomerExt::getOtherPhone, searchText));
        }
        return customerExtMapper.selectPage(page, lq);
    }

    @Override
    public PowerResourceSet queryResourcePower(String roleId, int pageIndex, int pageSize) {
        PowerResourceSet set = new PowerResourceSet("cust_source", "客户渠道", PowerTypeEnum.Customer_Source);

        //获取相应的权限
        List<String> roles = new ArrayList<>();
        roles.add(roleId);
        List<String> powers = appPowerService.queryResourcePower(roles, PowerTypeEnum.Customer_Source);
        if (powers == null) {
            return set;
        }
        if (powers.size() <= 0) {
            return set;
        }

        List<DictionaryValueExt> list = dictionaryValueService.queryValueByKey(CustomerConfigureCode.customer_source_dict);
        List<PowerResourceObject> records = new ArrayList<>();
        for (DictionaryValueExt value : list) {
            PowerResourceObject obj = new PowerResourceObject();
            obj.setId(value.getValue());
            obj.setCode(value.getValue());
            obj.setName(value.getDescription());
            obj.setDesc(value.getValue() + " : " + value.getDescription());
            obj.setChecked(powers.contains(value.getValue()));
            records.add(obj);
        }
        set.setPageRecord(records);
        return set;
    }

//    @Override
//    public List<String> queryNothingPower() {
//        return dictionaryValueService.queryDeletesByKey();
//    }
}